package com.bjpowernode.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.bjpowernode.constant.Constants;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;

@Controller
public class CaptchaController {

    @GetMapping(value = "/api/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) { //返回一张图片，图片是以文件流的方式返回给前端，所以方法返回void
        //生成干扰线是圆圈的图形验证码
        //ICaptcha iCaptcha = CaptchaUtil.createCircleCaptcha(100, 25, 4, 15);

        //生成干扰线是动态图片的图形验证码
        //ICaptcha iCaptcha = CaptchaUtil.createGifCaptcha(100, 25, 4);

        //生成干扰线是线条的图形验证码
        //ICaptcha iCaptcha = CaptchaUtil.createLineCaptcha(100, 25, 4, 35);

        ICaptcha iCaptcha = CaptchaUtil.createShearCaptcha(100, 25, 4, 2);

        //把验证码放入session中
        request.getSession().setAttribute(Constants.CAPTCHA, iCaptcha.getCode());

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //把验证码写出到浏览器客户端
            iCaptcha.write(outputStream);
            //刷新输出流的缓存区
            outputStream.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (outputStream != null) {
                //关闭输出流
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
